<template>
  <Spin :spinning="loading" tip="Loading...">
  <div>
    <!-- 索赔结算单查询-详情页面 -->
    <BreakSpace label="结算单汇总信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel ref="formPanel" :list="formList" :cols="3" :formType="'add'" labelWidth="110" :isSubmitBtn="false" @formChange="formChangeHandle" />
    <div style="padding-top: 2rem"></div>
    <BreakSpace label="结算单列表" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      ref="table"
      :columns="columns"
      :params="fetchParams"
      :datakey="'items'"
      :onColumnsChange="(columns) => (this.columns = columns)"
      :onRowSelectChange="selectChange"
      :is-select-column="false"
      :isSelectColumn="false"
      :isPagination="false"
      height="auto"
    >
      <template slot="controls" slot-scope="props">
        <el-button size="small" type="text" style="font-size: 14px; color: #bb2801; font-weight: bold">
          <span v-text="`每个批次只可维护同类车辆属性的结算单`"></span>
        </el-button>
        <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="jiesuandanadd()">添加</multiuse-button>
        <multiuse-button size="small" type="primary" icon="el-icon-plus" @click.once="jiesuandanalladd()">一键添加</multiuse-button>
      </template>
    </FilterTable>
    <BaseDialog :visible.sync="jiesuandanFlag" :title="'结算单选择'" width="900px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <SelectJieSuanDan @close="jiesuandanclose" @save="jiesuandansave" :rowData="rowData"></SelectJieSuanDan>
    </BaseDialog>
    <div style="padding-top: 3rem"></div>
    <BreakSpace label="审核列表" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      ref="table1"
      :columns="columns1"
      :params="fetchParams"
      :datakey="'items'"
      :onColumnsChange="(columns) => (this.columns = columns)"
      :onRowSelectChange="selectChange"
      :is-select-column="false"
      :isSelectColumn="false"
      :isPagination="false"
      height="auto"
    >
    </FilterTable>
    <div style="margin-bottom: 1rem"></div>
    <div style="padding-top: 3rem"></div>
    <div
      :style="{
        position: 'fixed',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right',
      }"
    >
      <multiuse-button type="primary" :click="saveDialog.bind()">保 存</multiuse-button>
      <multiuse-button @click="closeDialog">关 闭</multiuse-button>
    </div>
    <Drawer :visible.sync="chakanFlag" :title="'结算单详情'" destroyOnClose width="60%" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <showDetail @close="chakanFlag=false" :rowData="rowDate"></showDetail>
    </Drawer>
  </div>
  </Spin>
</template>
<script>
import { getPartType, newSave } from '@/api/claim/factory/ClaimAccountSummarySubmit';
import SelectJieSuanDan from './SelectJieSuanDan.vue';
import {  getAppId } from '@/assets/js/auth';
import { dictionary } from '@/utils/dictMixin';
import showDetail from "../ClaimStatementQueryFactory/showDetail";
import { qurListByPage } from '@/api/claim/factory/ClaimAccountSummarySubmit';
export default {
  mixins: [dictionary],
  components: {
    SelectJieSuanDan,showDetail
  },
  data() {
    return {
      loading: false,
      rowData: {},
      dataList: [],
      visible: false,
      jiesuandanFlag: false,
      visibleDrawer: false,
      jiesuansum: 0,
      fapiaozhangshusum: 0,
      flterValue: {}, //参数
      columns: this.creatHeader(),
      columns1: this.creatHeader1(),
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中经销商
      formList: this.createFormList(),
      saveData: null,
      rowDate:null,
      chakanFlag:false
    };
  },
  created() {
    this.loading = true;
   // this.chuqi();
    if (getAppId() == 'arcfox') {
      this.formList.find(x => x.fieldName == 'sumType').itemList =this.createDictList('5543',[55431001])
    }else{
      this.formList.find(x => x.fieldName == 'sumType').itemList =this.createDictList('5543')
    }
    this.chuqi2();
    this.loading = false;
  },
  methods: {
    //考核分类
    async chuqi2() {
      // const res = await getPartType({ type: 5543 });
      // if(getAppId()=='arcfox'){
      //   delete res.data[0]
      //   this.formList.find((x) => x.fieldName == 'sumType').initialValue = 55431002;
      // }
      // if (res.resultCode == 200) {
      //   this.formList.find((x) => x.fieldName == 'sumType').itemList = res.data.map((y) => ({ text: y.codeCnDesc, value: y.codeId }));
      // }

      //考核状态
      // const res1 = await getPartType({ type: 5547 });
      // if (res1.resultCode == 200) {
      //   this.formList.find((x) => x.fieldName == 'sumStatus').initialValue = 55471001;
      //   this.formList.find((x) => x.fieldName == 'sumStatus').itemList = res1.data.map((y) => ({
      //     text: y.codeCnDesc,
      //     value: y.codeId,
      //   }));
      // }


    },
    //结算单删除
    deleteFunjiesuan(costItem) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          this.$notify({
            title: '提示信息',
            message: '删除成功',
            type: 'success',
          });
          this.$refs.table.$refs.pageTable.EXECUTE_DELETE([costItem]);
          this.formList.map((x) => {
            if ('invoiceAmount' == x.fieldName) {
              x.initialValue = (this.jiesuansum - Number(costItem.settleSum)).toFixed(2);
              this.jiesuansum = this.jiesuansum - Number(costItem.settleSum);
            }
          });
          this.formList.map((x) => {
            if ('invoiceSheets' == x.fieldName) {
              x.initialValue = this.fapiaozhangshusum - Number(costItem.invoiceSheets);
              this.fapiaozhangshusum = this.fapiaozhangshusum - Number(costItem.invoiceSheets);
            }
          });
        })
    },
    //结算单状态
    async chuqi() {
      const res = await getPartType({ type: 5546 });
      if (res.resultCode == 200) {
        this.formList.find((x) => x.fieldName == 'sumStatus').initialValue = '';
        this.formList.find((x) => x.fieldName == 'sumStatus').itemList = res.data.map((y) => ({ text: y.codeCnDesc, value: y.codeId }));
      }
    },
    formChangeHandle(val) {
      console.log(val);
      this.saveData = val;
    },
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = val;
      console.log(val);
    },
    //结算单计算
    jiesuandansave(val) {
      let list = this.$refs.table.$refs.pageTable.list;
      let values = [];
      val.map((v) => {
        if (!list.find((x) => x.batchId == v.batchId)) {
          values.push(v);
        }
      });
      this.$refs.table.$refs.pageTable.EXECUTE_INSERT(values);
      //总金额
      let jiesuanjine = 0;
      this.$refs.table.$refs.pageTable.list.map((x) => {
        jiesuanjine += Number(x.settleSum);
      });
      this.formList.map((x) => {
        if ('invoiceAmount' == x.fieldName) {
          x.initialValue = Number(jiesuanjine).toFixed(2);
        }
      });
      this.jiesuansum = jiesuanjine;
      //发票张数
      let fapiaozhangshu = 0;
      this.$refs.table.$refs.pageTable.list.map((x) => {
        fapiaozhangshu += Number(x.invoiceSheets);
      });
      this.formList.map((x) => {
        if ('invoiceSheets' == x.fieldName) {
          x.initialValue = Number(fapiaozhangshu);
        }
      });
      this.fapiaozhangshusum = fapiaozhangshu;
      this.jiesuandanFlag = false;
    },
    suopeidanclose() {
      this.suopeidanFlag = false;
    },
    jiesuandanadd() {
      this.formList.find((x) => x.fieldName === 'sumType').rules = [{ required: true, message: '添加结算单前，请选择索赔车辆属性！', trigger: 'change' }];
      if (this.formList.find((x) => x.fieldName === 'sumType').initialValue) {
        this.$refs.formPanel.SUBMIT_FORM();
        this.rowData = this.saveData;
        this.jiesuandanFlag = true;
      }
    },
    jiesuandanclose() {
      this.jiesuandanFlag = false;
    },
    //一键添加方法
    async jiesuandanalladd() {
      this.formList.find((x) => x.fieldName === 'sumType').rules = [{ required: true, message: '添加结算单前，请选择索赔车辆属性！', trigger: 'change' }];
      if (this.formList.find((x) => x.fieldName === 'sumType').initialValue) {
         let res = await qurListByPage({appId: getAppId(),carType: this.formList.find(x => x.fieldName == 'sumType').initialValue,batchStatus:55481004,statusForFlag:3,current:1,currentPage:1,limit:1000,pageNum:1,pageSize:1000,size:1000});
         if (res.data.records.length <= 0) {
           return this.$notify.info({title: '提示信息', message: '无可添加的结算单!'});
         }else{
             console .log(res,"resresresresresresresresresresresresresresres")
             this.$refs.table.$refs.pageTable.EXECUTE_INSERT(res.data.records);
          }
       

      }
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
    },
    //保存
    async saveDialog() {
      this.$refs.formPanel.SUBMIT_FORM();
      let arr = [];
      let assessNum = 0;
      this.$refs.table.$refs.pageTable.list.map((x) => {
        delete x.isDeleted;
        arr.push(x);
        assessNum+=x.assessSum
      });
      //附加项目
      this.saveData.dtlList = arr;
      //新增时状态字典码为录入
      this.saveData.sumStatus = 55471001;
      this.saveData.assessSum= Number(assessNum).toFixed(2);
      if (this.saveData.dtlList.length !== 0 && this.saveData.sumType !== null) {
        let falg = true;
        this.saveData.carType = this.$refs.table.$refs.pageTable.list[0].carType;
        let firstCarType = this.saveData.carType;
        this.$refs.table.$refs.pageTable.list.map((x) => {
          if (x.carType !== firstCarType) {
            falg = false;
          }
        });
        if (falg) {
          this.loading = true;
          let res = await newSave(this.saveData);
          if (res.resultCode === 200) {
            this.$emit('save');
            return this.$notify.success({ title: '提示信息', message: '保存成功' });
          } else {
            this.loading = false;
            this.$notify.error({ title: '提示信息', message: res.errMsg || '保存失败!' });
          }
        } else {
          this.loading = false;
          this.$notify.error({ title: '提示信息', message: '所选结算单的车辆属性不一致，请维护同一类型车辆属性的结算单！' });
        }

        //
        //
        //
        //
        // let res = await newSave(this.saveData);
        // if (res.resultCode === 200) {
        //   this.closeDialog('refresh');
        //   return this.$notify.success({ title: '提示信息', message: '保存成功' });
        //   this.$emit('save');
        // } else {
        //   this.$notify.error({ title: '提示信息', message: res.errMsg || '保存失败!' });
        //   this.closeDialog();
        // }
      } else {
        return this.$notify.warning({ title: '提示信息', message: '有未校验通过的信息' });
      }
    },
    //取消操作
    closeDialog() {
      this.$emit('close', { visible: false, data: this.selectedRows, type: 'close' });
    },
    chooseOrderNo() {
      this.visible = true;
    },
    chakan(val) {
      this.rowDate = val;
      this.chakanFlag = true;
    },
    add() {},
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '结算汇总单号',
          fieldName: 'sumNo',
          initialValue: '',
          disabled: true,
        },
        {
          type: 'SELECT',
          label: '索赔车辆属性',
          fieldName: 'sumType',
          placeholder: '请选择',
          rules: [],
          initialValue: '',
          itemList: [],
          change: val => {
            let list = [...this.$refs.table.$refs.pageTable.list];
            this.$refs.table.$refs.pageTable.EXECUTE_DELETE(list);
            this.formList.find((x) => x.fieldName == 'invoiceSheets').initialValue = '';
            this.formList.find((x) => x.fieldName == 'invoiceAmount').initialValue = '';
          }
        },
        {
          type: 'SELECT',
          label: '单据状态',
          fieldName: 'sumStatus',
          initialValue: 55471001,
          itemList: this.createDictList('5547'),
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '发票张数',
          fieldName: 'invoiceSheets',
          initialValue: '',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '开票总金额',
          fieldName: 'invoiceAmount',
          initialValue: '',
          disabled: true,
        },
        {
          type: 'DATE_TIME',
          label: '提交时间',
          dateFormat: 'yyyy-MM-dd',
          fieldName: 'applyDate',
          initialValue: '',
          disabled: true,
        },
        {
          type: 'TEXT_AREA',
          label: '开票备注',
          selfCols: '3',
          fieldName: 'invoiceRemarks',
          initialValue: '',
          placeholder: '请输入开票备注...',
        },
      ];
    },
    //结算单列表
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          fixed: 'left',
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          render: (props) => {
            return (
              <div style="text-align:center">
                <multiuse-button size="mini" type="text" onClick={() => this.deleteFunjiesuan(props.row)}>
                  删除
                </multiuse-button>
                <el-divider direction="vertical" />
                <multiuse-button type="text" onClick={() => this.chakan(props.row)} >
                  详情
                </multiuse-button>
              </div>
            );
          },
        },
        { title: '经销商代码', dataIndex: 'dealerCode', sorter: true },
        { title: '经销商名称', dataIndex: 'dealerName', sorter: true },
        { title: '结算批次单号', dataIndex: 'batchNo', sorter: true },
        { title: '索赔单数', dataIndex: 'claimNum', sorter: true },
        { title: '发票张数', dataIndex: 'invoiceSheets', sorter: true },
        { title: '结算金额', dataIndex: 'settleSum', sorter: true },
        { title: '索赔金额', dataIndex: 'claimSum', sorter: true },
        { title: '考核金额', dataIndex: 'assessSum', sorter: true },
        // { title: '税额', dataIndex: 'settleStatusStr', sorter: true },
        { title: '工时费（元）', dataIndex: 'labourAmount', sorter: true },
        { title: '配件费用（元）', dataIndex: 'partAmount', sorter: true },
        { title: '附加费（元）', dataIndex: 'addAmount', sorter: true },
      ];
    },
    //审核列表
    creatHeader1() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        { title: '操作人', dataIndex: 'checkBy', sorter: true },
        { title: '操作时间', dataIndex: 'checkAt', sorter: true },
        { title: '操作后状态', dataIndex: 'statusStr', sorter: true },
        { title: '审核原因', dataIndex: 'checkRemarks', sorter: true },
      ];
    },
  },
};
</script>
<style lang="less" scoped></style>
